{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "    def islandPerimeter(self, grid):\n",
    "        \"\"\"\n",
    "        :type grid: List[List[int]]\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        num_land = 0\n",
    "        num_connected = 0\n",
    "        \n",
    "        h = len(grid)\n",
    "        w = len(grid[0])\n",
    "        \n",
    "        for i in range(h):\n",
    "            for j in range(w):\n",
    "                if grid[i][j] == 1:\n",
    "                    num_land += 1\n",
    "                    if i + 1 < h and grid[i+1][j] == 1:\n",
    "                        num_connected += 1\n",
    "                    if j + 1 < w and grid[i][j+1] == 1:\n",
    "                        num_connected += 1\n",
    "        \n",
    "        return num_land * 4 - 2 * num_connected"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = Solution()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.islandPerimeter([[0,1,0,0],[1,1,1,0],[0,1,0,0],[0,1,0,0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
